package bootstrap

import (
	"github.com/irisProject/config"
	"github.com/irisProject/utils/response"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
	"github.com/kataras/iris/sessions"
	"strings"
	"time"
)

//自定义配置函数
type Configurator func(*App)

type App struct {
	*iris.Application
	AppName      string
	AppSpawnDate time.Time
	Sessions     *sessions.Sessions
}

func (app *App) SetupViews() {
	templatesDir := config.Conf.Section("app").Key("templates_dir").String()
	templatesPrefix := config.Conf.Section("app").Key("templates_prefix").String()
	htmlEngine := iris.HTML(templatesDir, templatesPrefix)
	//热加载模板
	htmlEngine.Reload(true)
	app.RegisterView(htmlEngine)
}

func (app *App) SetupErrorHandlers() {
	app.OnAnyErrorCode(func(ctx iris.Context) {
		path := ctx.Path()
		//如果是api接口地址
		if strings.Index(path, "/api") == 0 {
			res.ApiException(ctx)
			return
		} else {
			res.RenderException(ctx)
			return
		}
	})
}

func (app *App) Configure(cs ...Configurator) *App {
	for _, c := range cs {
		c(app)
	}
	return app
}

func (app *App) Bootstrap() *App {
	app.SetupViews()
	app.SetupErrorHandlers()
	// static files
	app.StaticWeb("/assets", "./public")
	// middleware, after static files
	app.Use(recover.New())
	app.Use(logger.New())

	return app
}

func (app *App) Start(configs ...iris.Configurator) {
	addr := config.Conf.Section("app").Key("addr").String()
	port := config.Conf.Section("app").Key("port").String()
	err := app.Run(
		iris.Addr(addr+":"+port),
		configs...
	)
	if err != nil {
		panic(err)
	}

}

func New() *App {
	appName := config.Conf.Section("app").Key("name").String()
	app := &App{
		AppName:      appName,
		AppSpawnDate: time.Now(),
		Application:  iris.New(),
	}
	return app.Bootstrap()
}
